package br.com.agenciaBancaria.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.banco.entidades.Conta;

/**
 * Servlet implementation class ServletMessageProducer
 */
@WebServlet("/conta")
public class ServletMessageProducer extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletMessageProducer() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String QUEUE_LOOKUP = "queue/Conta";
        final String CONNECTION_FACTORY = "ConnectionFactory";
        
        PrintWriter out = response.getWriter();
        try{
            Context context = new InitialContext();
            
            QueueConnectionFactory factory =
                (QueueConnectionFactory)context.lookup(CONNECTION_FACTORY);
            
            QueueConnection connection = factory.createQueueConnection();
            
            QueueSession session =
                connection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);
 
            Queue queue = (Queue)context.lookup(QUEUE_LOOKUP);
            QueueSender sender = session.createSender(queue);
            
            ObjectMessage objMsg = session.createObjectMessage();
            
            out.println("Criando a conta");
            
            Conta conta = new Conta("1234");
            conta.setSaldo(10);
            
            objMsg.setObject(conta);
            sender.send(objMsg);
            
            out.println("Mensagem enviada");
            
            session.close();
        }catch(Exception e){
        	e.printStackTrace();
        	}
    }

}
